package com.sky.controller;

import com.sky.pojo.Student;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class CacheController {

    @Autowired
    private CacheManager cacheManager;

    @RequestMapping("/cache/add")
    @CachePut(cacheNames = "stu", key = "#result.id") //将数据添加至缓存
    public Student getPut(Integer id, String name, Integer age){
        log.info("执行CachePut注解, ---add---{}",id);
        return new Student(id,name,age);
    }

    @RequestMapping("/cache/find")
    @Cacheable(cacheNames = "stu", key = "#id") //判断数据是否已经缓存,如果没有缓存,就将数据添加至缓存,如果已经添加,就直接返回缓存数据
    public Student getAble(Integer id, String name, Integer age){
        log.info("执行Cacheable注解, ---find---{}",id);
        return new Student(id, "name", 18);
    }

    @RequestMapping("/cache/delete")
    @CacheEvict(cacheNames = "stu", allEntries = true)  //删除缓存
    public Student deleteAll(){
        log.info("执行CacheEvict注解, ---deleteAll---");
        return new Student(0, "delete",0);
    }
}
